<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="水源地名称" prop="status">
        <el-input
          v-model="queryParams.drinksourcename"
          placeholder="请输入水源地名称"
        />
      </el-form-item>
      <el-form-item label="水源地类型">
        <el-select
          v-model="queryParams.drinksourcetype"
          placeholder="请选水源地类型"
          clearable
        >
          <el-option
            v-for="item in dict.type.syd_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属区县">
        <el-select
          v-model="queryParams.countycode"
          placeholder="请选所属区县"
          filterable
          clearable
        >
          <el-option
            v-for="item in regionList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="水源地级别">
        <el-select
          v-model="queryParams.drinksourcelevel"
          placeholder="请选水源地级别"
          clearable
        >
          <el-option
            v-for="item in dict.type.syd_level"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="水源地编码" prop="status">
        <el-input
          v-model="queryParams.drinksourcecode"
          placeholder="请输入水源地编码"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >查询</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete(null)"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      style="width: 100%"
      :data="tableData"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="饮用水源地名称" prop="drinksourcename">
        <template #default="{ row }">
          <a href="#" @click.prevent="handleEdit(row)">{{
            row.drinksourcename
          }}</a>
        </template>
      </el-table-column>
      <el-table-column label="饮用水源地编码" prop="drinksourcecode" />
      <el-table-column label="所属区县" prop="county" />
      <el-table-column label="水源地类型" prop="drinksourcetype">
        <template #default="{ row }">
          {{ row.drinksourcetype | dictType(dict.type.syd_type) }}
        </template>
      </el-table-column>
      <el-table-column label="服务人口（万人）" prop="populationcovered" />
      <el-table-column label="设计取水量（万吨/年）" prop="designwithdrawal" />
      <el-table-column fixed="right" label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button size="mini" type="text" @click="handleEdit(row)"
            >修改</el-button
          >
          <el-button size="mini" type="text" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-show="total > 0"
      :current-page="queryParams.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryParams.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :pager-count="5"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="900px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="140px"
        size="small"
        :rules="formRules"
      >
        <el-row>
          <el-col :span="12">
            <!-- 饮用水源地名称 -->
            <el-form-item label="饮用水源地名称" prop="drinksourcename">
              <el-input
                v-model="formData.drinksourcename"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 饮用水源地编码 -->
            <el-form-item label="饮用水源地编码" prop="drinksourcecode">
              <el-input
                v-model="formData.drinksourcecode"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 行政区划  county-->
            <el-form-item label="行政区划" prop="countycode">
              <el-select
                v-model="formData.countycode"
                placeholder="请选择行政区划"
                filterable
                clearable
                style="width: 100%"
                @change="
                  formChange($event, 'code', { county: 'name' }, regionList)
                "
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 水源地类型 -->
            <el-form-item label="水源地类型" prop="drinksourcetype">
              <el-select
                v-model="formData.drinksourcetype"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.syd_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 对应水厂 -->
            <el-form-item label="对应水厂" prop="waterworks">
              <el-input
                v-model="formData.waterworks"
                placeholder="请输入对应水厂"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 设计取水量 -->
            <el-form-item label="设计取水量" prop="designwithdrawal">
              <el-input
                v-model="formData.designwithdrawal"
                placeholder="请输入设计取水量"
              >
                <template slot="append">(万吨/年)</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 实际取水量 -->
            <el-form-item label="实际取水量" prop="actualwithdrawal">
              <el-input
                v-model="formData.actualwithdrawal"
                placeholder="请输入实际取水量"
              >
                <template slot="append">(万吨/年)</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 水源地建成时间 -->
            <el-form-item label="水源地建成时间" prop="completiondate">
              <el-date-picker
                style="width: 100%"
                v-model="formData.completiondate"
                type="date"
                placeholder="请选择水源地建成时间"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 正式取水时间 -->
            <el-form-item label="正式取水时间" prop="withdrawaldate">
              <el-date-picker
                style="width: 100%"
                v-model="formData.withdrawaldate"
                type="date"
                placeholder="请选择正式取水时间"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 是否跨界水源 -->
            <el-form-item label="是否跨界水源" prop="isboundarysource">
              <el-select
                v-model="formData.isboundarysource"
                placeholder="请选择是否跨界水源"
                clearable
                style="width: 100%"
              >
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 服务人口 -->
            <el-form-item label="服务人口" prop="populationcovered">
              <el-input
                v-model="formData.populationcovered"
                placeholder="请输入服务人口"
              >
                <template slot="append">(万人)</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 经度 -->
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="formData.longitude" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 纬度 -->
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="formData.latitude" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 水源井个数 -->
            <el-form-item label="水源井" prop="wellscount">
              <el-input
                v-model="formData.wellscount"
                placeholder="请输入水源井个数"
              >
                <template slot="append">(个)</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!-- 水源地级别 -->
            <el-form-item label="水源地级别" prop="drinksourcelevel">
              <el-select
                v-model="formData.drinksourcelevel"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.syd_level"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 使用状态 -->
            <el-form-item label="使用状态" prop="usestatus">
              <el-select
                v-model="formData.usestatus"
                placeholder="请选择"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.syd_use_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- 简介 -->
            <el-form-item label="简介" prop="introduction">
              <el-input
                v-model="formData.introduction"
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 新增：水源地图片上传区域（字段改为drinksourceimage） -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="水源地图片" prop="drinksourceimage">
              <el-upload
                :action="baseUrl + '/common/upload'"
                :headers="headers"
                accept="image/jpeg,image/gif,image/png,image/jpg"
                list-type="picture-card"
                :limit="5"
                :file-list="imagePreviewList"
                :on-preview="handleImagePreview"
                :on-remove="handleImageRemove"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
              >
                <i class="el-icon-plus"></i>
              </el-upload>

              <!-- 上传提示 -->
              <div style="margin-top: 10px; color: #666; font-size: 12px">
                提示：最多上传5张图片，单张不超过500KB，支持JPG/PNG/GIF格式
              </div>

              <!-- 图片预览弹窗 -->
              <el-dialog
                :visible.sync="imageDialogVisible"
                append-to-body
                width="80%"
                title="图片预览"
              >
                <div class="preview-container">
                  <img
                    width="100%"
                    :src="imageDialogUrl"
                    alt="图片预览"
                    class="preview-media"
                  />
                </div>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 新增：水源地视频上传区域（字段drinksourcevideo） -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="水源地视频" prop="drinksourcevideo">
              <!-- 视频上传组件 -->
              <el-upload
                :action="baseUrl + '/common/upload'"
                :headers="headers"
                accept="video/mp4,video/avi,video/mov,video/flv,video/wmv"
                list-type="text"
                :limit="1"
                :file-list="videoFileList"
                :on-remove="handleVideoRemove"
                :on-success="handleVideoSuccess"
                :before-upload="beforeVideoUpload"
                :on-preview="handleVideoPreview"
              >
                <el-button size="mini" type="primary" icon="el-icon-upload"
                  >选择视频文件</el-button
                >
              </el-upload>

              <!-- 上传提示 -->
              <div style="margin-top: 10px; color: #666; font-size: 12px">
                提示：仅支持上传1个视频文件，大小不超过100MB，支持MP4/AVI/MOV/FLV/WMV格式
              </div>

              <!-- 已上传视频预览（编辑/查看时显示） -->
              <div
                v-if="videoPreviewUrl"
                class="video-preview-container"
                style="margin-top: 15px"
              >
                <el-button
                  type="text"
                  icon="el-icon-play"
                  @click="showVideoPlayer = true"
                  style="color: #409eff; margin-bottom: 10px"
                >
                  播放已上传视频
                </el-button>
                <div class="video-info">
                  <span>文件名称：{{ videoFileName || "未知文件" }}</span>
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    @click="handleVideoRemove(null, [])"
                    style="color: #f56c6c; margin-left: 20px"
                  >
                    删除
                  </el-button>
                </div>
              </div>

              <!-- 视频播放弹窗 -->
              <el-dialog
                :visible.sync="showVideoPlayer"
                append-to-body
                width="80%"
                title="视频播放"
                :before-close="handleVideoPlayerClose"
              >
                <div class="video-player-container">
                  <video
                    :src="videoPreviewUrl"
                    controls
                    autoplay
                    style="width: 100%; max-height: 600px"
                  >
                    您的浏览器不支持HTML5视频播放，请更新浏览器版本
                  </video>
                </div>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getdrinksourcelist,
  removedrinksource,
  adddrinksource,
  editdrinksource,
} from "./api/baseinfo";
import { validatorLongitude, validatorLatitude } from "@/utils/validate";
import { getRegionList } from "@/api/dataResources/monitorData/region";
import { getToken } from "@/utils/auth";

export default {
  name: "reportManagement",
  dicts: ["syd_type", "syd_level", "syd_use_type"],
  components: {},
  data() {
    return {
      // 遮罩层
      loading: false,
      total: 0,
      // 显示搜索条件
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      regionList: [],
      tableData: [],
      selectedRows: [],
      dialogVisible: false,
      dialogType: "add",
      formRules: {
        drinksourcename: [
          { required: true, message: "请输入水源地名称", trigger: "blur" },
        ],
        drinksourcecode: [
          { required: true, message: "请输入水源地编码", trigger: "blur" },
        ],
        drinksourcetype: [
          { required: true, message: "请选择水源地类型", trigger: "change" },
        ],
        longitude: [
          { validator: validatorLongitude, required: true, trigger: "blur" },
        ],
        latitude: [
          { validator: validatorLatitude, required: true, trigger: "blur" },
        ],
        drinksourceimage: [
          { required: false, message: "请至少上传1张图片", trigger: "change" }, // 可改为true设为必填
        ],
        drinksourcevideo: [
          { required: false, message: "请上传视频文件", trigger: "change" }, // 可改为true设为必填
        ],
      },
      formData: {
        id: "",
        drinksourcename: "",
        drinksourcecode: "",
        county: "",
        countycode: "",
        drinksourcetype: "",
        rivername: "",
        rivercode: "",
        lakename: "",
        lakecode: "",
        waterworks: "",
        designwithdrawal: "",
        actualwithdrawal: "",
        completiondate: "",
        withdrawaldate: "",
        istransboundary: "",
        transboundarytype: "",
        populationcovered: "",
        longitude: "",
        latitude: "",
        introduction: "",
        drinksourceimage: "", // 图片字段改为drinksourceimage（逗号分隔字符串）
        drinksourcevideo: "", // 视频字段drinksourcevideo（单个文件路径）
        usestatus: "",
        drinksourcelevel: "",
        wellscount: "",
        intakestage: "",
        drystage: "",
      },
      // 图片上传相关配置
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      imagePreviewList: [], // 图片预览列表
      imageFileNames: [], // 图片文件名数组
      // 图片预览弹窗
      imageDialogVisible: false,
      imageDialogUrl: "",

      // 视频上传相关配置
      videoFileList: [], // 视频文件列表（限制1个）
      videoFileName: "", // 视频文件名
      videoPreviewUrl: "", // 视频预览地址
      showVideoPlayer: false, // 视频播放器弹窗控制
    };
  },
  computed: {
    title() {
      if (this.dialogType == "add") {
        return "添加水源地基础信息";
      } else {
        return "编辑水源地基础信息";
      }
    },
  },
  created() {
    this.getRegionListFn();
    this.getList();
  },
  filters: {
    dictType(value, list) {
      let item = list.find((it) => it.value == value);
      return item ? item.label : "";
    },
  },
  methods: {
    formChange(value, key, map, list) {
      let item = list.find((it) => it[key] == value);
      if (item) {
        for (let fkey in map) {
          this.formData[fkey] = item[map[fkey]];
          console.log("fkey", fkey, this.formData[fkey]);
        }
      }
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    async getRegionListFn() {
      let res = await getRegionList(0);
      this.regionList = res.rows;
    },
    async getList() {
      this.loading = true;
      let res = await getdrinksourcelist(this.queryParams);
      this.tableData = res.rows;
      this.total = res.total;
      this.loading = false;
    },

    handleEdit(row) {
      this.formData = { ...row };

      // 图片回显：处理drinksourceimage字段（逗号分隔字符串）
      const imageUrls = row.drinksourceimage
        ? row.drinksourceimage.split(",").filter((url) => url)
        : [];
      // 核心修改：为回显的图片添加response属性，与上传成功的图片结构一致
      this.imagePreviewList = imageUrls.map((url) => ({
        url: process.env.VUE_APP_BASE_API + url,
        status: "success",
        response: { fileName: url }, // 手动添加response属性，存储原始文件名
      }));
      this.imageFileNames = [...imageUrls];
      this.formData.drinksourceimage = this.imageFileNames.join(",");

      // 视频回显：处理drinksourcevideo字段（单个文件路径）
      if (row.drinksourcevideo) {
        this.videoFileName =
          row.drinksourcevideo.split("/").pop() || "视频文件"; // 提取文件名
        this.videoPreviewUrl =
          process.env.VUE_APP_BASE_API + row.drinksourcevideo;
        this.videoFileList = [
          {
            name: this.videoFileName,
            url: this.videoPreviewUrl,
            status: "success",
          },
        ];
      } else {
        this.videoFileName = "";
        this.videoPreviewUrl = "";
        this.videoFileList = [];
      }

      this.dialogType = "edit";
      this.dialogVisible = true;
    },
    handleAdd() {
      this.formData = {
        id: "",
        drinksourcename: "",
        drinksourcecode: "",
        county: "",
        countycode: "",
        drinksourcetype: "",
        rivername: "",
        rivercode: "",
        lakename: "",
        lakecode: "",
        waterworks: "",
        designwithdrawal: "",
        actualwithdrawal: "",
        completiondate: "",
        withdrawaldate: "",
        istransboundary: "",
        transboundarytype: "",
        populationcovered: "",
        longitude: "",
        latitude: "",
        introduction: "",
        drinksourceimage: "",
        drinksourcevideo: "",
        usestatus: "",
        drinksourcelevel: "",
        wellscount: "",
        intakestage: "",
        drystage: "",
      };
      // 重置图片相关
      this.imagePreviewList = [];
      this.imageFileNames = [];
      this.formData.drinksourceimage = "";

      // 重置视频相关
      this.videoFileList = [];
      this.videoFileName = "";
      this.videoPreviewUrl = "";
      this.showVideoPlayer = false;
      this.formData.drinksourcevideo = "";

      this.dialogType = "add";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["formRef"].resetFields();
      });
    },
    async handleDelete(row) {
      let ids = [];
      if (row) {
        ids.push(row.id);
      } else {
        ids = this.selectedRows.map((item) => item.id);
      }
      if (!ids[0]) {
        return this.$message.warning("请选择要删除的行");
      }
      let res = await this.$confirm(`确定删除吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return true;
        })
        .catch(() => {
          return false;
        });
      if (res) {
        await removedrinksource(ids.join(","));
        this.$message.success("删除成功");
        this.getList();
      }
    },
    submitForm() {
      this.$refs["formRef"].validate((res) => {
        if (res) {
          // 构造提交参数
          const submitData = {
            ...this.formData,
            drinksourceimage: this.imageFileNames.join(","), // 图片：数组转逗号分隔字符串
            drinksourcevideo: this.videoFileName
              ? this.videoFileName // 核心修复：直接使用videoFileName（后端返回的文件路径）
              : "", // 视频：单个文件路径
          };

          let fn = this.dialogType == "add" ? adddrinksource : editdrinksource;
          fn(submitData).then((res) => {
            this.$message.success("操作成功");
            this.dialogVisible = false;
            this.getList();
          });
        }
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // ===================== 图片相关方法 =====================
    // 图片预览
    handleImagePreview(file) {
      this.imageDialogUrl = file.url;
      this.imageDialogVisible = true;
    },

    // 图片上传成功
    handleImageSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.imageFileNames.push(response.fileName);
        this.imagePreviewList = fileList;
        this.formData.drinksourceimage = this.imageFileNames.join(",");
      }
    },

    // 图片移除（核心修复：处理两种场景的图片删除）
    handleImageRemove(file, fileList) {
      // 场景1：上传成功的图片（有response属性）
      // 场景2：编辑回显的图片（已在handleEdit方法中手动添加response属性）
      const fileName = file.response?.fileName;

      if (fileName) {
        // 从文件名数组中移除当前图片
        this.imageFileNames = this.imageFileNames.filter(
          (item) => item !== fileName
        );
      } else {
        // 异常情况处理：如果没有fileName，通过url提取
        const url = file.url;
        if (url) {
          const extractFileName = url.replace(this.baseUrl + "/", "");
          this.imageFileNames = this.imageFileNames.filter(
            (item) => item !== extractFileName
          );
        }
      }

      this.imagePreviewList = fileList; // 更新回显列表
      this.formData.drinksourceimage = this.imageFileNames.join(","); // 重新拼接字符串

      // 调试用（可删除）：查看删除后的文件名数组
      console.log("删除后的图片数组：", this.imageFileNames);
    },

    // 图片上传前校验
    beforeImageUpload(file) {
      const isImage =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/jpg";
      const isLt500k = file.size / 1024 < 500;

      if (!isImage) {
        this.$message.error("上传图片只能是 JPG/PNG/GIF 格式!");
      }
      if (!isLt500k) {
        this.$message.error("上传图片大小不能超过 500KB!");
      }
      return isImage && isLt500k;
    },

    // ===================== 视频相关方法 =====================
    // 视频上传成功
    handleVideoSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.videoFileName = response.fileName;
        this.formData.drinksourcevideo = this.videoFileName; // 直接存储后端返回的文件路径
        this.videoPreviewUrl =
          process.env.VUE_APP_BASE_API + this.videoFileName;
        this.videoFileList = fileList;
        this.$message.success("视频上传成功！");
      }
    },

    // 视频移除
    handleVideoRemove(file, fileList) {
      this.videoFileList = fileList;
      this.videoFileName = "";
      this.videoPreviewUrl = "";
      this.formData.drinksourcevideo = "";
      this.showVideoPlayer = false;
    },

    // 视频上传前校验
    beforeVideoUpload(file) {
      // 支持的视频格式
      const videoTypes = [
        "video/mp4",
        "video/avi",
        "video/mov",
        "video/flv",
        "video/wmv",
      ];
      const isVideo = videoTypes.includes(file.type);
      const isLt100M = file.size / 1024 / 1024 < 100; // 限制100MB

      if (!isVideo) {
        this.$message.error("上传视频只能是 MP4/AVI/MOV/FLV/WMV 格式!");
      }
      if (!isLt100M) {
        this.$message.error("上传视频大小不能超过 100MB!");
      }
      return isVideo && isLt100M;
    },

    // 视频预览（上传组件的preview事件）
    handleVideoPreview() {
      if (this.videoPreviewUrl) {
        this.showVideoPlayer = true;
      }
    },

    // 关闭视频播放器
    handleVideoPlayerClose() {
      // 暂停视频播放，避免关闭弹窗后仍有声音
      const video = document.querySelector(".video-player-container video");
      if (video) {
        video.pause();
      }
      this.showVideoPlayer = false;
    },
  },
};
</script>
<style lang="scss" scoped>
// 图片上传样式
.el-upload--picture-card {
  width: 100px;
  height: 100px;
  margin-right: 10px;
}

// 修复图片变形问题
::v-deep .el-upload-list__item-image {
  object-fit: contain !important;
  max-width: 100%;
  max-height: 100%;
}

// 媒体预览弹窗样式
::v-deep .el-image-viewer__wrapper {
  z-index: 9999 !important;
}

.preview-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.preview-media {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

// 视频预览区域样式
.video-preview-container {
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.video-info {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

// 视频播放器容器样式
.video-player-container {
  padding: 10px;
  background-color: #000;
  border-radius: 4px;
}

// 解决el-upload文本模式下的样式问题
::v-deep .el-upload--text {
  .el-upload__input {
    display: none;
  }
}
</style>
